package Service;

import domain.Card;
import utils.Tools;
import java.io.IOException;
import java.text.ParseException;


public class CardService {
    static Tools tools = new Tools();
    public static void openAccount(String userId) throws IOException {
        if (tools.getCardByUserId(userId) != null) {
            System.out.println("该用户已存在卡！");
            return;
        }
        Card card = new Card();
        int cardId = tools.getID("cardId");
        card.setCardId("C" + cardId);
        card.setUserId(userId);
        card.setBalance(0);
        card.setStatus("正常");
        cardId++;
        tools.setID("cardId", cardId);
        tools.setCard(card);

        System.out.println("开户成功！");
        System.out.println("您的卡账号为" + card.getCardId() + ",请牢记");
    }

    public static void changeCardStatus(String cardId, String status) throws IOException {
        Card card = tools.getCardByUserId(cardId);
        if (card != null) {
            card.setStatus(status);
            System.out.println("卡状态更新为：" + status);
            tools.setCard(card);
        } else {
            System.out.println("卡不存在！");
        }
    }

    public static void recharge(String userId, double amount) throws IOException, ParseException {
        Card card = tools.getCardByUserId(userId);
        if (card != null && card.getStatus().equals("正常")) {
            card.setBalance(card.getBalance() + amount);
            System.out.println("充值成功，当前余额：" + card.getBalance());
            tools.setCard(card);
            TransactionService.saveCardBalance(userId, "充值", amount);

        } else {
            System.out.println("充值失败，卡状态异常，请联系管理员。");
        }
    }

    public static void consume(String userId, double amount) throws IOException, ParseException {
        Card card = tools.getCardByUserId(userId);
        if (card != null && card.getStatus().equals("正常")) {
            if (card.getBalance() >= amount) {
                card.setBalance(card.getBalance() - amount);
                System.out.println("消费成功，当前余额：" + card.getBalance());
                tools.setCard(card);
                TransactionService.saveCardBalance(userId, "消费", amount);
            } else {
                System.out.println("余额不足！");
            }
        } else {
            System.out.println("消费失败，卡状态异常。");
        }
    }

    public static double getBalance(String userId) throws IOException {
        return tools.getCardByUserId(userId).getBalance();
    }

    public static void deleteCard(String userId) throws IOException {
        tools.removeCardByUserId(userId);
        System.out.println("卡删除成功！");
    }
}
